#include "Task.hpp"
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <unistd.h>
#include <functional>
#include <ctime>
#include <sys/types.h>
#include <sys/wait.h>

const int proccessnum = 5;

std::vector<std::function<void()>> task{
    []() { std::cout << "task0" << std::endl; },
    []() { std::cout << "task1" << std::endl; },
    []() { std::cout << "task2" << std::endl; },
    []() { std::cout << "task3" << std::endl; },
};

class channel {
public:
    channel(int cmdfd, int slaverid, const std::string& proccessname) :
     _cmdfd(cmdfd), _slaverid(slaverid), _processname(proccessname) {}

public:
    int _cmdfd;
    pid_t _slaverid;
    std::string _processname;
};


void slaver() {
    while (true) {
        int cmdcode;
        read(0, &cmdcode, sizeof(int));   //没有内容，阻塞等待
        task[cmdcode]();
    }
}

class Channels {
public:
    Channels() {
        for (int i = 0; i < proccessnum; i++) {
        int pipefd[2];
        int n = pipe(pipefd);
        
        pid_t id = fork();
        if (id == 0) {
            close(pipefd[1]);
            dup2(pipefd[0], 0);
            close(pipefd[0]);
            slaver();
            exit(0);
        }
        close(pipefd[0]);
        std::string name = "process-" + std::to_string(i);
        channels.push_back(channel(pipefd[1], id, name));
        }
    }

    ~Channels() {
        for (auto& c : channels) {
            close(c._cmdfd);
            waitpid(c._slaverid, nullptr, 0);
        }
        std::cout << "exit success" << std::endl;
    }


    void ChoseSlaver() {
        int which = 0;
        while (true) {
        int cmdcode;
        std::cin >> cmdcode;
            write(channels[which]._cmdfd, &cmdcode, sizeof(int));
            which = (which + 1) % (int)channels.size();
            sleep(1);
        } 
    }
private:
    std::vector<channel> channels;
};
int main() {
    srand(time(nullptr));
    Channels cnl;
    cnl.ChoseSlaver();
}